import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router'
import store from "@/store";

const routes: Array<RouteRecordRaw> = [
  {
    path: '/',
    name: 'home',
    component: () => import("@/views/web/index/WebIndexView.vue"),
  },
  {
    path: '/adm',
    name: 'adm',
    component: () => import("@/views/adm/login/AdminLogin.vue"),
  },
  {
    path: '/adm:pathMatch(.*)*',
    redirect: '/adm'
  },
  {
    path: '/:pathMatch(.*)*',
    redirect: '/'
  }
]

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes
});

/**
 * 清除管理端的路由
 */
const clearAdminRoute = function () {
  router.removeRoute("adm-index");
  router.addRoute({
    path: '/adm-index',
    name: 'adm-index',
    component: () => import("@/views/adm/login/AdminIndex.vue")
  });
  // 添加子路由
  router.addRoute("adm-index", { path: "", name: "adm-welcome", component: () => import("@/views/adm/login/AdminWelcome.vue") })
  // router.addRoute("adm-index", { path: "article", name: "article-list", component: () => import(url) })
}

/**
 * 添加管理员的路由
 * @param obj 路由对象
 */
const addAdminRoute = (obj: IFun) => {
  // 有个部分嵌套了两层
  const arr = obj.path.split("/");
  const imports = obj.import_path.split(",");
  const params = obj.params?.split(",");
  let parentName = "adm-index";
  for (const i in arr) {
    if (!router.hasRoute(arr[i])) {
      let path = arr[i];
      let props = undefined;
      if (params && params[i]) {
        path += params[i];
        props = (route:any) => ({params:route.params});
      }
      const options = {path,name:arr[i],component: () => import(`@/views/adm${imports[i]}`),props};
      console.log(parentName,options,`@/views/adm${imports[i]}`);
      router.addRoute(parentName, options);
      parentName = arr[i];
    }
  }
}

/**
 * 重新设置路由，并根据store中的数据，加载动态路由
 */
 const setAdminRoute = function () {
  const admin = store.state.admin;
  console.log("重新设置动态路由");
  clearAdminRoute();
  admin.funList?.forEach(v => {
    v.funs.forEach(v2 => {
      // 列表
      if (v2.path && v2.import_path) {
        addAdminRoute(v2);
      }
    })
  })
}


export {setAdminRoute }
export default router